package leetcode_day._2021._202104._1120;

import java.util.Arrays;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/4/20 8:51
 * 实现 strStr() 函数
 * 循环遍历
 * <p>
 * 双指针 m n
 * kmp 算法
 * next 数组表示当前结尾的最大前后缀相同的字符的个数
 */
public class _20_28 {
    public static void main(String[] args) {
        String needle = "ababab";
        int[] next = new int[needle.length()];
        for (int i = 1, j = 0; i < needle.length(); i++) {
            while(j > 0 && needle.charAt(i) != needle.charAt(j)) j = next[j - 1];
            if (needle.charAt(i) == needle.charAt(j)) ++j;
            next[i] = j;
        }
        System.out.println(Arrays.toString(next));
    }

    public int strStr_kmp(String haystack, String needle) {
        if (needle.length() == 0) return 0;
        int m = haystack.length(), n = needle.length();
        int[] next = new int[n];
        for (int i = 1, j = 0; i < n; i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) j = next[j - 1];
            if (needle.charAt(i) == needle.charAt(j)) ++j;
            next[i] = j;
        }
        for (int i = 0, j = 0; i < m; i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = next[j - 1];
            if (haystack.charAt(i) == needle.charAt(j)) ++j;
            if (j == n) return i - n + 1;
        }
        return -1;
    }

    public int strStr(String haystack, String needle) {
        int m = haystack.length(), n = needle.length();
        if (m < n) return -1;
        for (int i = 0; i < m - n + 1; i++)
            if (needle.equals(haystack.substring(i, i + n))) return i;
        return -1;
    }
}
